package com.example.its2021606134chh.ETCModule;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: MyDataAdapter$
 * @Description: 作用
 * @Author: letquit
 * @CreateDate: 5/7/2021$
 * @Version: 1.0
 */
public class MyDataAdapter {
    private MySQLiteOpenHelper openHelper;
    private SQLiteDatabase database;
    public void openDB(Context context) {
        openHelper = new MySQLiteOpenHelper(context, "ETCaccount1.db", null, 1);
        try {
            database = openHelper.getWritableDatabase();
        } catch (Exception e) {
            database = openHelper.getReadableDatabase();
        }
    }
    public void closeDB() {
        if (database != null) {
            database.close();
            database = null;
        }
        if (openHelper != null) {
            openHelper.close();
            openHelper = null;
        }
    }
    public List<Cars> QueryAll (Context context) {
        List<Cars> carsList = new ArrayList<>();
        openDB(context);
        Cursor cursor = database.query("etccar", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                int carID = cursor.getInt(0);
                int carBalance = cursor.getInt(1);
                int carRecharge = cursor.getInt(2);
                String user = cursor.getString(3);
                String time = cursor.getString(4);
                carsList.add(new Cars(carID, carBalance, carRecharge, user, time));
            } while (cursor.moveToNext());
        }
        cursor.close();
        closeDB();
        return carsList;
    }
    public long insert(Context context, Cars cars) {
        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
        String sNow = ft.format(dNow);
        openDB(context);
        ContentValues values = new ContentValues();
        values.put("carID", cars.getCarID());
        values.put("carBalance", cars.getCarBalance());
        values.put("carRecharge", cars.getCarRecharge());
        values.put("user", "user1");
        values.put("time", sNow);
        long result = database.insert("etccar", null, values);
        closeDB();
        return result;
    }
}
